package com.test.bindservice.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import com.test.bindservice.IMyAidlInterface;
import com.test.bindservice.constatns.Constant;

/**
 * 保活进程
 */
public class GuardService extends Service {

    private Binder myBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if(!ToolsUtils.isServiceRunning(GuardService.this, Constant.PUSH_SERVICE_NAME)){
                startService(new Intent(GuardService.this,PushService.class));
            }
            bindService(new Intent(GuardService.this,PushService.class), serviceConnection, Context.BIND_IMPORTANT);
            Log.i(Constant.TAG, "RestartProcess PushService:");

        }
    };;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        if(serviceConnection != null){
            unbindService(serviceConnection);
        }
        super.onDestroy();
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bindService(new Intent(this,PushService.class), serviceConnection, Context.BIND_IMPORTANT);
        return super.onStartCommand(intent, START_STICKY, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        myBinder = new MyBinder();
        return myBinder;
    }

    public static class MyBinder extends IMyAidlInterface.Stub{

        @Override
        public void onRestartProcess(String processName) throws RemoteException {
            Log.i(Constant.TAG, "GuardService onRestartProcess: "+ processName);
        }
    }

}
